package org.example.sudoku.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import static org.example.sudoku.database.ConstantsDB.KEY_GAME;
import static org.example.sudoku.database.ConstantsDB.KEY_DESCRIPTION;
import static org.example.sudoku.database.ConstantsDB.KEY_ROWID;
import static org.example.sudoku.database.ConstantsDB.KEY_DIFICULTY;
import static org.example.sudoku.database.ConstantsDB.DB_TABLE;

public class SudokuDbAdapter {

	
	private Context context;
	private SQLiteDatabase database;
	private SudokuDatabaseHelper dbHelper;

	public SudokuDbAdapter(Context context) {
		this.context = context;
	}

	public SudokuDbAdapter open() throws SQLException {
		dbHelper = new SudokuDatabaseHelper(context);
		database = dbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		dbHelper.close();
	}

	public long createGame(String game, String dificulty, String description) {
		ContentValues values = createContentValues(game, dificulty,
				description);

		return database.insert(DB_TABLE, null, values);
	}

	public boolean updateGame(long rowId, String game, String dificulty,
			String description) {
		ContentValues values = createContentValues(game, dificulty,
				description);

		return database.update(DB_TABLE, values, KEY_ROWID + "=" + rowId, null) > 0;
	}

	public boolean deleteGame(long rowId) {

		return database.delete(DB_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	public Cursor fetchGame(long rowId) throws SQLException {
		
		Cursor mCursor = database.query(true, DB_TABLE, new String[] {
				KEY_ROWID, KEY_GAME, KEY_DIFICULTY, KEY_DESCRIPTION },
				KEY_ROWID + "=" + rowId, null, null, null, null, null);

		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;

	}

	private ContentValues createContentValues(String game, String dificulty,
			String description) {
		ContentValues values = new ContentValues();

		values.put(KEY_GAME, game);
		values.put(KEY_DIFICULTY, dificulty);
		values.put(KEY_DESCRIPTION, description);
		return values;
	}

	public Cursor fetchAllTodos() {
		return database.query(DB_TABLE, new String[] { KEY_ROWID, KEY_GAME,
				KEY_DIFICULTY, KEY_DESCRIPTION }, null, null, null, null, null);
		//return fetchTodo(0);
	}

}
